﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using PSLib.Parsing.Common;
using Microsoft.VisualStudio.Text;

namespace LuaLanguageExtension.Parsing
{
    public static class SnapshotExtension
    {
        public static ElementSpan GetElementSpan(this SnapshotSpan snapshotSpan)
        {
            ElementSpan span = new ElementSpan();
            span.Start = snapshotSpan.Start.GetElementPosition();
            span.End = snapshotSpan.End.GetElementPosition();
            return span;
        }

        public static ElementPosition GetElementPosition(this SnapshotPoint snapshotPoint)
        {
            ITextSnapshotLine line = snapshotPoint.GetContainingLine();
            return new ElementPosition(line.LineNumber + 1, snapshotPoint.Position - line.Start.Position);
        }

        public static SnapshotSpan GetSnapshotSpan(this RecognizedToken token, ITextSnapshot snapshot)
        {
            int globalStartPosition = token.NativeToken.GetPosition().GetGlobalPosition(snapshot);
            int tokenLenght = token.NativeToken.Text.Length;
            if(globalStartPosition == -1) return new SnapshotSpan();

            return new SnapshotSpan(snapshot,new Span(globalStartPosition,tokenLenght));
        }

        public static int GetGlobalPosition(this ElementPosition elementPosition, ITextSnapshot snapshot)
        {
            int result = -1;
            ITextSnapshotLine line = snapshot.GetLineFromLineNumber(elementPosition.Line - 1);
            if (line != null) result = line.Start.Position + elementPosition.PositionInLine;
            return result;
        }
    }
}
